package org.suyafei.controller;

import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.suyafei.controller.request.SendCodeRequest;
import org.suyafei.enums.BizCodeEnum;
import org.suyafei.enums.SendCodeEnum;
import org.suyafei.service.NotifyService;
import org.suyafei.utils.CommonUtil;
import org.suyafei.utils.JsonData;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author 宿某人
 * @Date: 2021/12/09/11:10 上午
 * @Description:
 */
@RestController
@RequestMapping("/api/notify/v1")
@Slf4j
public class NotifyController {

    @Autowired
    private Producer captchaProducer;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private NotifyService notifyService;

    public static final long CAPTCHA_CODE_EXPIRED = 10;

    @GetMapping("captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) {
        String captchaText = captchaProducer.createText();
        log.info("验证码内容{}", captchaText);


        //存储redis,配置过期时间
        String captchaKey = getCaptchaKey(request);
        redisTemplate.opsForValue().set(captchaKey, captchaText, CAPTCHA_CODE_EXPIRED, TimeUnit.MINUTES);


        BufferedImage image = captchaProducer.createImage(captchaText);
        try( ServletOutputStream outputStream = response.getOutputStream();) {
            ImageIO.write(image, "jpg", outputStream);
            outputStream.flush();
        } catch (IOException e) {
            log.error("验证码流输出错误:{}", e.getMessage());
        }
    }

    /**
     * 获取验证码存入redis的key
     * @param request
     * @return
     */
    private String getCaptchaKey(HttpServletRequest request) {
        String ip = CommonUtil.getIpAddr(request);
        String userAgent = request.getHeader("User-Agent");
        String captchaKey = "server-account:captcha:" + CommonUtil.MD5(ip + userAgent);
        return captchaKey;
    }

    @PostMapping("send_code")
    public JsonData sendCode(@RequestBody SendCodeRequest sendCodeRequest, HttpServletRequest request) {
        String key = getCaptchaKey(request);

        //获取验证码
        String cacheCaptcha = redisTemplate.opsForValue().get(key);

        String captcha = sendCodeRequest.getCaptcha();

        if (captcha != null && cacheCaptcha != null && captcha.equalsIgnoreCase(cacheCaptcha)) {
            redisTemplate.delete(key);
            JsonData jsonData = notifyService.sendCode(SendCodeEnum.USER_REGISTER, sendCodeRequest.getTo());
            return jsonData;
        }else {
            return JsonData.buildResult(BizCodeEnum.CODE_CAPTCHA_ERROR);
        }
    }
}
